
import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Button, Modal, Form, Input, Row, Col, Table, Card, Icon, message } from 'antd';
import { connect } from 'dva';
// import styles from './style.less';

import PublicTableWrapper from '@/components/TableForm'


function beautySub(str, len) {
    const reg = /[\u4e00-\u9fa5]/g
    const slice = str.substring(0, len)
    // eslint-disable-next-line no-bitwise
    const chineseCharNum = (~~(slice.match(reg) && slice.match(reg).length))
    const realen = slice.length*2 - chineseCharNum
    return str.substr(0, realen) + (realen < str.length ? "..." : "")
}

const routes = [
    {
      path: '',
      breadcrumbName: 'Mange  user',
    },
    {
      path: '',
      breadcrumbName: 'Mange  account',
    }
]

// 新增管理员
const AddAdministrator = Form.create()(
    // eslint-disable-next-line react/prefer-stateless-function
    class extends React.Component {
      render() {
        const { visible, onCancel, onCreate, form,  } = this.props
        const { getFieldDecorator } = form
        const formItemLayout = { labelCol: { span: 5 }, wrapperCol: { span: 17 } }

        return (
            <Modal
                visible={visible}
                title="Add user"
                onCancel={onCancel}
                onOk={onCreate}
                forceRender
            >
                <Form style={{ margin: '0 auto' }}>
                    <Row gutter={24}>
                        <Col span={24}>
                            <Form.Item label="Account" {...formItemLayout} >
                                {getFieldDecorator('accout', {
                                rules: [{ required: true, message: 'Input account!' }],
                                })(<Input placeholder="Input account" />)}
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item label="Name" {...formItemLayout} >
                                {getFieldDecorator('name', {
                                rules: [{ required: true, message: 'Input Name!' }],
                                })(<Input placeholder="Input Name" />)}
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item label="Password" {...formItemLayout} >
                                {getFieldDecorator('pwd', {
                                    rules: [{ required: true, message: 'Input!' }, { min: 5, message: "Input a password of at least 5 digits"}],
                                })(<Input.Password placeholder="Input a password of at least 5 digits" />)}
                            </Form.Item>
                        </Col>
                        
                        
                    </Row>
                </Form>
            </Modal>
        )
      }
    }
)


// 关联网关
const AboutGateWay = Form.create()(
    // eslint-disable-next-line react/prefer-stateless-function
    class extends React.Component {
      state = {
        data: [
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
        ],
        columns: [
            {
                title: 'GW IMEI',
                dataIndex: 'Code',
            },
            {
                title: 'Operation',
                dataIndex: 'option',
                valueType: 'option',
                width: 150,
                render: (_, record) => (
                    <>
                        <a 
                            style={{color: 'red'}}
                            onClick={() => this.deleteClick(record)}
                        >
                            delete
                        </a>
                    </>
                ),
            },
        ],
      }

    handleSearch = () => {
        const { form, gatewaysListSearch } = this.props
        
        form.validateFields((err, values) => {
            if (err) { return}
            if (values.accout !== undefined && values.accout !== "") {
                gatewaysListSearch(values)
            }
        })
        
    }

    handleReset = () => {
        this.props.form.resetFields()
    }

    deleteClick = record => {
        const { gatewaysDelete } = this.props
        gatewaysDelete(record)
    }

    render() {
        const { visible, onCancel, onCreate, form,  } = this.props
        const { getFieldDecorator } = form
        const formItemLayout = { labelCol: { span: 5 }, wrapperCol: { span: 17 } }

        return (
            <Modal
                visible={visible}
                title="Manage Assgn’d GW"
                onCancel={onCancel}
                onOk={onCreate}
                // forceRender
                width="60%"
            >
                <>
                    <Form style={{ margin: '0 auto' }}>
                        <Row gutter={24}>
                            <Col span={8}>
                                <Form.Item label={false} {...formItemLayout} required={false}>
                                    <Icon type="search" />
                                    {getFieldDecorator('accout', { })(
                                        <Input placeholder="Input GW IMEI"
                                            style={{width: '80%', marginLeft: '10px', borderTop: '0px', borderLeft: '0px', borderRight: '0px'}}
                                        />
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={8}>
                            <Form.Item style={{ display: 'flex' }}>
                                <Button type="primary" htmlType="submit" onClick={this.handleSearch}>
                                Query
                                </Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                                Reset
                                </Button>
                            </Form.Item>
                        </Col>
                        </Row>
                    </Form>
                    <Table
                        rowKey="key"
                        dataSource={this.props.data}
                        columns={this.state.columns}
                        pagination={{
                            defaultPageSize: 7
                        }}
                    ></Table>
                </>
            </Modal>
        )
      }
    }
)

@connect(({ manageandaccout }) => ({
    manageandaccout
}))


class Management extends Component {
    state = {
        // 新增管理员弹窗
        visible: false,
        // 关联网关弹窗
        gatewayVisible: false,
        // 关联网关数据
        gatewaysList: [],
        // 关联网关原始数据
        gatewaysOringeList: [],
        // 关联网关编辑对象
        gatewaysEditObj: {},
        // data: [
        //     {
        //         key: '2',
                // user_accout: 'yifei',
                // user_name: '一飞',
                // create_time: '2016-09-21  08:50',
                // connec_gateway: ['357404109951002','357404109951002','357404109951002'],
        //     },
        //     {
        //         key: '1',
        //         user_accout: 'yifei',
        //         user_name: '一飞',
        //         create_time: '2016-09-21  08:50',
        //         connec_gateway: ['357404109951002'],
        //     }
        // ],
        columns: [
            {
                title: 'Account',
                dataIndex: 'user_accout',
            },
            {
                title: 'Name',
                dataIndex: 'user_name',
            },
            {
                title: 'Creation time',
                dataIndex: 'create_time',
            },
            {
                title: 'Assgn’d GW',
                dataIndex: 'connec_gateway',
                render: (_, record) => (
                    <>
                        <a
                            onClick={() => this.showGateway(_, record)}
                        >{beautySub(record.connec_gateway.join('、'), 9)}</a>
                    </>
                ),
            },
            {
                title: 'Operation',
                dataIndex: 'option',
                valueType: 'option',
                render: (_, record) => (
                    <>
                        {/* <a
                            // onClick={() => this.toCompanyInfo(_, record)}
                        >
                            scan
                        </a> */}
                        {/* <Divider type="vertical" />
                        <a
                            onClick={() => this.toCompanyInfo(_, record)}
                        >
                            编辑
                        </a> */}
                        {/* <Divider type="vertical" /> */}
                        <a 
                            style={{color: 'red'}}
                            onClick={() => this.userDeleteClick(record)}
                        >
                            delete
                        </a>
                    </>
                ),
            },
        ],

        loading: false,
        data: [],
        page: 1,
        pageSize: 10,
        search: "",
        totalCount: 1,

        
    }

    componentDidMount () {
        this.initfetch()
    }

    initfetch = () => {
        const { dispatch } = this.props
        const { page, pageSize, search } = this.state
        this.setState({loading: true})
        dispatch({
            type: 'manageandaccout/fetch',
            payload: {
                limit: pageSize,
                offset: (page - 1) * pageSize,
                search,
              },
        }).then(res => {
            if (res.status === 200) {
                this.setState({
                    data: res.data,
                    loading: false,
                    totalCount: res.totalPageSize,
                })
            } else {
                this.setState({
                    data: [],
                    loading: false,
                    totalCount: 0,
                })
            }
        })
    }
    
    userDeleteClick = record => {
        const isThis = this
        const { dispatch } = this.props
        // deleteUser
        Modal.confirm({
            title: 'confirm deletion',
            content: (<div><span style={{color: 'red'}}>The deletion is irrevocable.</span><span style={{color: '#5E5E5E'}}>Do you want to continue?</span></div>),
            onOk() {
                dispatch({
                    type: 'manageandaccout/deleteUser',
                    payload: record
                }).then(res => {
                    if (res.status === 200) {
                        isThis.initfetch()
                        message.success('success')
                    } else {
                        message.error('fail')
                    }
                })
                
            },
            onCancel() {},
        })
    }


    // 分页
    paginationChange = (page, pageSize) => {
        this.setState({
            page,
            pageSize,
        })
        
        const { dispatch } = this.props
        const { search } = this.state
        this.setState({loading: true})
        dispatch({
            type: 'manageandaccout/fetch',
            payload: {
                limit: pageSize,
                offset: (page - 1) * pageSize,
                search,
              },
        }).then(res => {
            if (res.status === 200) {
                this.setState({
                    data: res.data,
                    loading: false,
                    totalCount: res.totalPageSize,
                })
            } else {
                this.setState({
                    data: [],
                    loading: false,
                    totalCount: 0,
                })
            }
        })
    }

    saveFormRef = formRef => { this.formRef = formRef }

    // 关联网关的form绑定
    saveGateWayFormRef = formRef => { this.saveGateWayFormRef = formRef }

    // 关联网关弹窗
    showGateway = (_, record) => {
        this.setState({
            // 设置关联网关展示数据
            gatewaysList: record.gatewaysList,
            // 设置关联网关原始数据
            gatewaysOringeList: record.gatewaysList,
            // 弹窗
            gatewayVisible: true,
            // 设置关联网关编辑对象
            gatewaysEditObj: record
        })
    }

    // 关联网关搜索
    gatewaysListSearch = values => {
        const { gatewaysOringeList } = this.state
        const data = []
        gatewaysOringeList.map(item => {
            if (item.Code.includes(values.accout)) {
                data.push(item)
            }
            return 200
        })
        this.setState({
            gatewaysList: data
        })
    }

    // 关联网关删除
    gatewaysDelete = record => {
        const { dispatch } = this.props
        dispatch({
            type: 'manageandaccout/updateUser',
            payload: {
                userId: this.state.gatewaysEditObj.id,
                gatewayId: record.Id
            },
        }).then(res => {
            if (res.status === 200) {
                const { gatewaysOringeList } = this.state
                // eslint-disable-next-line array-callback-return
                gatewaysOringeList.map((item, index) => {
                    if (item.Id === record.Id) {
                        gatewaysOringeList.splice(index, 1)
                    }
                })
                this.setState({
                    gatewaysOringeList
                })
            }
        })

    }
    
    // 新增用户弹窗
    showModal = () => { this.setState({ visible: true }) }

    // 新增用户弹窗确认
    onCreate = () => {
        const { form } = this.formRef.props
        const { dispatch } = this.props

        form.validateFields((err, values) => {
            if (err) { return}
            dispatch({
                type: 'manageandaccout/addUser',
                payload: values,
            }).then(res => {
                if (res.status === 200) {
                    this.setState({
                        visible: false
                    })
                    this.initfetch()
                }
            })



        })
    }

    // 所有弹窗取消
    onCancel = () => {
        this.setState({ visible: false, gatewayVisible: false })
    }

    handleSearch = () => {
        const { form } = this.props
        const mapObj = {
            search_useraccout: 'accout__contains',
        }
        const searchList = []
        form.validateFields((err, values) => {
            if (err) { return}
            if (values.search_useraccout !== "" && values.search_useraccout !== undefined) {
                Object.keys(values).forEach(key => {
                    if (values[key] !== undefined && values[key] !== '' ) {
                      searchList.push(`${mapObj[key]}:${values[key]}`);
                    }
                  })
            }

        })
        const searchString = `&query=${searchList.join(',')}`;
        // search record
        this.setState({
            search: searchString,
        })
        // fetch data
        const { dispatch } = this.props
        const { page, pageSize } = this.state
        this.setState({loading: true})
        dispatch({
            type: 'manageandaccout/fetch',
            payload: {
                limit: pageSize,
                offset: (page - 1) * pageSize,
                search: searchString
              },
        }).then(res => {
            if (res.status === 200) {
                this.setState({
                    data: res.data,
                    loading: false,
                    totalCount: res.totalPageSize,
                })
            } else {
                this.setState({
                    data: [],
                    loading: false,
                    totalCount: 0,
                })
            }
        })
    }

    handleReset = () => {
        this.props.form.resetFields()
    }

    render () {
        const formItemLayout = { labelCol: { span: 5 }, wrapperCol: { span: 17 } }
        const { getFieldDecorator } = this.props.form

        return (
            <PageHeaderWrapper title="Mange  account" breadcrumb={{ routes }}>
                <Card>
                    <Row gutter={24}>
                        <Col span={8}>
                            <Form.Item label="Account" {...formItemLayout}>
                                {getFieldDecorator('search_useraccout')(<Input placeholder="Input account" />)}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item style={{ display: 'flex' }}>
                                <Button type="primary" htmlType="submit" onClick={this.handleSearch}>
                                Query
                                </Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                                Reset
                                </Button>
                            </Form.Item>
                        </Col>
                    
                    </Row>

                    <Button icon="plus" type="primary" style={{marginBottom: '10px'}} onClick={this.showModal}>Add user</Button>


                    <PublicTableWrapper
                        loading={this.state.loading}
                        columns={this.state.columns}
                        data={this.state.data}
                        currentpageSize={this.state.pageSize}
                        total={this.state.totalCount}
                        paginationChange={(page, pageSize) => this.paginationChange(page, pageSize)}
                    />
                </Card>

                <AddAdministrator
                    wrappedComponentRef={this.saveFormRef}
                    visible={this.state.visible}
                    onCancel={this.onCancel}
                    onCreate={this.onCreate}
                />

                <AboutGateWay
                    wrappedComponentRef={this.saveGateWayFormRef}
                    visible={this.state.gatewayVisible}
                    onCancel={this.onCancel}
                    onCreate={this.onCancel}
                    data={this.state.gatewaysList}
                    gatewaysListSearch={this.gatewaysListSearch}
                    gatewaysDelete={this.gatewaysDelete}
                />

                
            </PageHeaderWrapper>
        )

    }

}



// export default Management
export default Form.create()(Management)